package setting

import (
	"epg-mc/database/table/config"
	"errors"
	"net/http"

	"github.com/labstack/echo"
)

var base *Base

//Base template data
type Base struct {
	data map[string]interface{}
}

func init() {
	base = &Base{data: make(map[string]interface{})}
	base.data["title"] = config.GetValue(config.SiteTitle)
	base.data["uname"] = ""
}

//Index url:/admin/setting/index
func Index(c echo.Context) error {
	base.data["uname"] = c.Get("uname")
	base.data["data"] = config.GetAll()
	err := c.Render(http.StatusOK, "setting/index.html", base.data)

	return err
}

//New url:/admin/setting/new
func New(c echo.Context) error {
	base.data["uname"] = c.Get("uname")
	if c.Request().Method() == "GET" {
		err := c.Render(http.StatusOK, "setting/add.html", base.data)
		return err
	}

	key := c.FormValue("config[key]")
	val := c.FormValue("config[value]")
	if key == "" || val == "" {
		return errors.New("Key, Value can not be empty")
	}
	comment := c.FormValue("config[comment]")
	group := c.FormValue("config[group]")
	cf := &config.Config{
		Key:     key,
		Value:   val,
		Comment: comment,
		Group:   group,
	}

	if err := config.Save(cf); err != nil {
		c.Error(err)
	}

	err := c.Redirect(http.StatusFound, "/admin/setting/index")
	return err
}

//Edit url:/admin/setting/edit/:key
func Edit(c echo.Context) error {
	base.data["uname"] = c.Get("uname")
	key := c.Param("key")
	if key == "" {
		c.Error(errors.New("Key can not be empty"))
	}
	if c.Request().Method() == "GET" {
		base.data["data"] = config.FindByKey(key)
		err := c.Render(http.StatusOK, "setting/edit.html", base.data)
		return err
	}

	val := c.FormValue("config[value]")
	if val == "" {
		c.Error(errors.New("Value can not be empty"))
	}
	comment := c.FormValue("config[comment]")
	group := c.FormValue("config[group]")

	oldConf := config.FindByKey(key)
	oldConf.Value = val
	oldConf.Comment = comment
	oldConf.Group = group

	if err := config.Save(oldConf); err != nil {
		c.Error(err)
	}
	err := c.Redirect(http.StatusFound, "/admin/setting/index")
	return err
}

//Delete url:/admin/setting/delete/:key
func Delete(c echo.Context) (err error) {
	result := make(map[string]string)
	if c.Request().Method() == "POST" {
		key := c.Param("key")
		err = config.Delete(key)
		if err != nil {
			result["error"] = err.Error()
		}
	}
	result["message"] = "OK"
	err = c.JSON(http.StatusOK, result)
	return err
}

//Consul url:/admin/setting/consul
func Consul(c echo.Context) error {
	base.data["uname"] = c.Get("uname")
	base.data["data"] = config.FindByKey(config.ConsulAddr)
	base.data["token"] = config.GetValue(config.ConsulEpgViewKey)
	err := c.Render(http.StatusOK, "setting/consul.html", base.data)
	if err != nil {
		c.Error(err)
	}
	return err
}
